package org.example.novel.security.handler;


import org.example.novel.utlis.BeanHelper;
import org.example.novel.utlis.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常处理类
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {

        Result<Object> fail = null;

        if (e instanceof BadCredentialsException){
            fail = Result.fail(401,e.getMessage());
        }else{
            fail = Result.fail(401,"认证失败,无法访问资源");
        }

        httpServletResponse.setCharacterEncoding("UTF-8");

        httpServletResponse.setContentType("application/json;charset=utf-8;");

        String s = BeanHelper.toJsonStr(fail);

        httpServletResponse.getWriter().write(s);

    }
}
